#!/usr/bin/env python
# encoding: utf-8
#----------------------------------------------------------------------------
#	Name: comic_unpack.py
#	Author: Doug Russell
#	Last Modified: 02-10-2008
#	Created with Python 2.5.2
#	Description: Unpack .cbr and .cbz files into web friendly folders
#	Requires rar and unrar binaries from rarlabs in /usr/bin
#	RarFile module will need to be installed
#----------------------------------------------------------------------------
#	Copyright (C) 2008 Doug Russell
#	
#	This program is free software: you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation, either version 3 of the License, or
#	(at your option) any later version.
#	
#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#	
#	
#	You should have received a copy of the GNU General Public License
#	along with this program.  If not, see <http://www.gnu.org/licenses/>.
#	
from Tkinter import *
import Tkinter, Tkconstants, tkFileDialog, tkSimpleDialog
import os, sys, re, string, rarfile, zipfile, comic  # Comic is a custom module

# TK modules for gui
# os module for interacting with the filesystem
# re module offers Regular Expression functions
# string module offers string data type processing, i.e. string.lower()
# rarfile module allows the inspection of rar archives
# zipfile module allows the inspection, creation, expansion of zip archives
# comic modules can decompress .cbr and .cbz comic archives and create
# web galleries from the resulting images
#
# Class to implement TKinter GUI
parent_directory = os.getcwd()
imgal_check = 0
rename_check = 0
gui_check = 1
for argument in sys.argv:
	if argument.startswith('--'):
		if argument[2:] == 'img':
			imgal_check = 1
			print 'imgal'
		elif argument[2:] == 'r':
			rename_check = 1
			print 'rename'

class ComicGui(Tkinter.Frame):
	def __init__(self, root):
		
		Tkinter.Frame.__init__(self, root)
		# options for buttons
		button_opt = {'fill': Tkconstants.BOTH, 'padx': 5, 'pady': 5}
		
		# define buttons
		Tkinter.Button(self, text='Decompress An Individual Comic Archive', \
		command=self.askopenfilename).pack(**button_opt)
		Tkinter.Button(self, text='Decompress A Directory Of Archives', \
		command=self.askdirectory).pack(**button_opt)
		Tkinter.Button(self, text='Compress A Single Directories (CBr)', \
		command=self.compdirectory).pack(**button_opt)
		Tkinter.Button(self, text='Compress A Directory of Directories (CBr)'\
		, command=self.compdirectories).pack(**button_opt)
		Tkinter.Button(self, text='Quit', \
		command=self.quit).pack(**button_opt)
		
		# defining options for opening or saving a file
		self.file_opt = options = {}
		options['defaultextension'] = ''
		options['filetypes'] = [('all files', '.*'), ('text files', '.txt')]
		options['parent'] = root
		options['title'] = 'Open Comic Book Archive'
		
		# defining options for opening or saving a file
		self.dir_opt = options = {}
		options['mustexist'] = False
		options['parent'] = root
		options['title'] = 'Open Directory'
	
	def askopenfilename(self):
		
		# get filename
		filename = tkFileDialog.askopenfilename(**self.file_opt)
		[parent, cwd] = comic.PathSplitter(filename)
		os.chdir(parent)
		# open file on your own
		if os.path.isfile(filename):
			if rarfile.is_rarfile(filename):
				# Passes archive to decompression function
				print "Attempting To Decompress " + cwd
				comic.UnRarComic(filename)
				print "Done"
			elif zipfile.is_zipfile(filename):
				print "Attempting To Decompress " + cwd
				comic.UnZipComic(filename)
				print "Done"
			else:
				print "Not An Archive"
	
	def askdirectory(self):
		"""Returns a selected directoryname."""
		print 'Established directory'
		directory = tkFileDialog.askdirectory(**self.dir_opt)
		if os.path.isdir(directory):
			# Switch into working directory
			os.chdir(directory)
			# Storing the initial working directory for later reference
			parent_dir = directory
			print 'Changed Directories'
			# Read in a list of files in current directory
			filelist = os.listdir(os.getcwd())
			
			
			# Storing the initial working directory for later reference
			# Loop to search for files that are comic archives and decompress them
			for file in filelist:
				print 'File Selected'
				if string.lower(file).find('.cbr') != -1: # Identifies Comic Book Rar
					# Certifies valid rar archive
					if rarfile.is_rarfile(os.path.join(parent_dir, file)):
						# Passes archive to decompression function
						print 'Is Rar'
						comic.UnRarComic(file)
						print 'Unrar Successful'
					else: # If archive  fails to validate, tests if it is a zip archive
						if zipfile.is_zipfile(os.path.join(parent_dir, file)):
							print 'Is Zip'
							os.rename(os.path.join(parent_dir, file), \
							os.path.join(parent_dir, file[0:-1] + 'z')) # rename to .cbz
							file  = file[0:-1] + 'z' # Update filelist for renamed file
							# Passes archive to decompression function
							comic.UnZipComic(file)
							print 'Unzip Successful'
						else: # If file doesn't validate as either zip or rar, skip
							print file + ' is neither a rar nor a zip'
				elif string.lower(file).find('.cbz') != -1: # Similar to cbr functions, but for cbz
					if zipfile.is_zipfile(os.path.join(parent_dir, file)):
						print 'Is Zip'
						comic.UnZipComic(file)
						print 'Unzip Successful'
					else:
						if rarfile.is_rarfile(os.path.join(parent_dir, file)):
							print 'Is Rar'
							os.rename(os.path.join(parent_dir, file), \
							os.path.join(parent_dir, file[0:-1] + 'r'))
							file = file[0:-1] + 'r'
							print 'Unrar Successful'
						else:
							print file + ' is neither a rar nor a zip'
			print 'Done'
	
	def compdirectory(self):
		print 'Established directory'
		directory = tkFileDialog.askdirectory(**self.dir_opt)
		if os.path.isdir(directory):
			if os.name == 'posix':
				split_dir = string.split(directory, '/')
				parent = string.join(split_dir[0:-1], '/')
				cwd = split_dir[-1]
			elif sys.platform == 'win32':
				print 'Untested'
				split_dir = string.split(directory, '\\')
				parent = string.join(split_dir[0:-1], '\\')
				cwd = split_dir[-1]
			os.chdir(parent)
			print 'Changed Directories'
			comic.RarComic(cwd)
			print 'Done With ' + cwd
	
	def compdirectories(self):
		print 'Established directory'
		directory = tkFileDialog.askdirectory(**self.dir_opt)
		if os.path.isdir(directory):
			os.chdir(directory)
			print 'Changed Directories'
			folderlist = os.listdir(os.getcwd())
			# Read in a list of folders in current directory
			for folder in folderlist:
				if os.path.isdir(folder):
					comic.RarComic(folder)
					print 'Done With ' + folder
		print 'Done'
	

class Naming(Tkinter.Frame):
	def __init__(self, master, submaster):
		
		Tkinter.Frame.__init__(self, master)
		button_opt = {'fill': Tkconstants.BOTH, 'padx': 5, 'pady': 5}
		
		self.e1 = Entry(submaster)
		self.e1.pack()
		self.e1.delete(0, END)
		self.e1.config(width='40')
		self.e1.insert(0, "Leader")
		self.e1.grid()
		
		self.e2 = Entry(submaster)
		self.e2.pack()
		self.e2.delete(0, END)
		self.e2.config(width='40')
		self.e2.insert(0, "File Extension")
		self.e2.grid()
		
		# options for buttons
		# define buttons
		Tkinter.Button(self, text='Rename', \
		command=self.ReName).grid()
		Tkinter.Button(self, text='Directory', \
		command=self.askdirectory).grid()
		# defining options for opening or saving a file
		self.file_opt = options = {}
		options['defaultextension'] = ''
		options['filetypes'] = [('all files', '.*'), ('text files', '.txt')]
		options['parent'] = root
		options['title'] = 'Open Comic Book Archive'
		
		# defining options for opening or saving a file
		self.dir_opt = options = {}
		options['mustexist'] = False
		options['parent'] = root
		options['title'] = 'Open Directory'
	
	def rename(self):
		Tkinter.Frame.__init__(self, submaster)
	
	def ReName(self):
		directory = self.dir
		lead = self.e1.get()
		ext = self.e2.get()
		os.chdir(directory)
		list = os.listdir(os.getcwd())
		index = 1
		for file in list:
			if os.path.isfile(file):
				name =  {'leader': lead, "#": index, 'follower': ext}
				rename = '%(leader)s %(#)03d.%(follower)s' % name
				print 'Renaming ' + rename
				os.rename(os.path.join(os.getcwd(), file), os.path.join(os.getcwd(), rename))
				index = index + 1
	
	def askdirectory(self):
		"""Returns a selected directoryname."""
		self.dir = tkFileDialog.askdirectory(**self.dir_opt)

class ImGal(Tkinter.Frame):
	def __init__(self, config, subconfig):
		Tkinter.Frame.__init__(self, config)
		button_opt = {'fill': Tkconstants.BOTH, 'padx': 5, 'pady': 5}
		self.e1 = Entry(subconfig)
		self.e1.pack()
		self.e1.delete(0, END)
		self.e1.config(width='40')
		self.e1.insert(0, "Directory")
		self.e1.grid()
		self.e2 = Entry(subconfig)
		self.e2.pack()
		self.e2.delete(0, END)
		self.e2.config(width='40')
		self.e2.insert(0, "Icons Per Row")
		self.e2.grid()
		self.e3 = Entry(subconfig)
		self.e3.pack()
		self.e3.delete(0, END)
		self.e3.config(width='40')
		self.e3.insert(0, "Maximum Width (false for none)")
		self.e3.grid()
		self.e4 = Entry(subconfig)
		self.e4.pack()
		self.e4.delete(0, END)
		self.e4.config(width='40')
		self.e4.insert(0, "Maximum Height (false for none)")
		self.e4.grid()
		Tkinter.Button(self, text='Generate Config.ini.php', \
		command=self.configure).pack(**button_opt)
	
	def Configure(self):
		Tkinter.Frame.__init__(self, subconfig)
	
	def configure(self):
		directory = self.e1.get()
		icons = self.e2.get()
		width = self.e3.get()
		height = self.e4.get()
		top = '<?php\n\n/**\n * @package\t\timgal: Image Gallery and File Browser' + \
		'\n * @name \t\timgal Configuration File\n * @author\t\tMasoud Gheysari ' + \
		'M <me@gheysari.com>\n * @license\t\tGPLv3\n * @copyright \t2009 Masoud ' + \
		'Gheysari M\n */\n\t\n\tdefine(ROOT_PATH\t\t,\''
		middle_1 = '\');\t// physical root path where you want to browse.\n\t' + \
		'define(SHOW_THUMBNAIL\t\t,false);\t\t\t// if set to true, imgal shows ' + \
		'thumbnail for images.\n\tdefine(FAST_RENDER\t\t,true);\t\t\t// if set to' + \
		' true, thumbnail images will render more quickly but with less quality.' + \
		'\n\t//define(HERO_PASSWORD\t\t,\'imgal\');\t\t// password of the hero ' + \
		'user (the superuser) who can upload files.\n\tdefine(MAX_THUMB_WIDTH\t' + \
		'\t,96);\n\tdefine(MAX_THUMB_HEIGHT\t\t,64);\n\tdefine(ICONS_PER_ROW\t\t,'
		middle_2 = ');\n\tdefine(PREVIEW_TEXT_FILES\t,true);\t\t\t// should imgal' + \
		' preview text files.\n\tdefine(PREVIEW_HTML_FILES\t,true);\t\t\t// ' + \
		'should imgal preview html files.\n\tdefine(PREVIEW_CODE_FILES\t,true);' + \
		'\t\t\t// should imgal preview code files.\n\tdefine(SHOW_NAMES_BESIDE\t' + \
		',false);\t\t// should imgal show file/folder names beside icons (or below' + \
		' them). need more work.\n\tdefine(DOWNLOAD_ZIP_DIR\t\t,true);\t\t\t// ' + \
		'directories can be downloaded as a zip file\n\tdefine(DOWNLOAD_TAR_DIR' + \
		'\t\t,false);\t\t\t// directories can be downloaded as a tar file\n\t' + \
		'define(TEMP_PATH\t\t,\'./\');\t\t\t// temporary path for storing zipped' + \
		' files\n\tdefine(DEFAULT_LANGUAGE\t\t,\'english\');\t// default ' + \
		'interface language\n\tdefine(SEARCH_ENABLE\t\t,true);\t\t\t// should ' + \
		'imgal let users to search.\n\tdefine(CHANGE_LANG_ENABLE\t,true);\t\t\t//' + \
		' should imgal let users to change language.\n\tdefine(MAX_WIDTH\t\t,'
		middle_3 = ');\t\t// set maximum image width, set to false for no maximum' + \
		' width.\n\tdefine(MAX_HEIGHT\t\t,'
		bottom = ');\t\t\t// set maximum image height, set to false for no maximum' + \
		' width.\n\tdefine(HEADER_COLOR\t\t,aaaaaa);\t\t// hex color for header' + \
		'\n\tdefine(BODY_COLOR\t\t,abcdef);\t\t// hex color for body\n\tdefine(' + \
		'FOOT_COLOR\t\t,888888);\t\t// hex color for footer\n\tdefine(VER_SIZE\t' + \
		'\t\t,2);\t\t\t// size of imgal-version text\n\tdefine(VER_COLOR\t\t,' + \
		'darkred);\t\t// color of imgal-version text\n\tdefine(BOX_TEXT_COLOR\t' + \
		'\t,111111);\t\t// color of text in form buttons\n\tdefine(IMAGE_LINK\t' + \
		'\t,true);\t\t\t// if set to true, each image is a link to the next\n\t' + \
		'define(GALLERY_MESSAGE\t\t,\'Comic Book Gallery\');\t// set banner ' + \
		'message in header\n\n?>'
		f = open(os.path.join(os.path.join(parent_directory, 'imgal'), 'config.ini.php'), 'w') 
		f.writelines(top)
		f.write(directory)
		f.writelines(middle_1)
		f.write(icons)
		f.writelines(middle_2)
		f.write(width)
		f.writelines(middle_3)
		f.write(height)
		f.writelines(bottom)
		f.close()
	

# Start TKinter Event Loop
if __name__=='__main__':
	root = Tkinter.Tk()
	ComicGui(root).pack()
	if rename_check == 1:
		master = Tkinter.Tk()
		submaster = Tkinter.Tk()
		Naming(master, submaster).pack()
		master.title("Rename")
		master.minsize(100,60)
		master.geometry("120x60")
		submaster.title("Rename Variables")
		submaster.minsize(300,50)
		submaster.geometry("300x50")
	if imgal_check == 1:
		config = Tkinter.Tk()
		subconfig = Tkinter.Tk()
		ImGal(config, subconfig).pack()
		config.title("Image Gallery")
		config.minsize(100,30)
		config.geometry("150x50")
		subconfig.title("Image Gallery Variables")
		subconfig.minsize(250,100)
		subconfig.geometry("300x100")
	root.title("Unpack Repack")
	root.mainloop()